package cn.chaos.bio01;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPEchoServer {

    private static final int BUF_SIZE = 32;
    
    private static int recvMsgSize;
    private static byte[] receiveBuf = new byte[BUF_SIZE];
    
    public static void main(String[] args) {
        
        int servPort = 11111;


        boolean running = true;
        
        try (ServerSocket serverSocket = new ServerSocket(servPort);) {
            while (running ) {  // NOSONAR
                handSocket(serverSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void handSocket(ServerSocket serverSocket) {
        
        try (Socket socket = serverSocket.accept();) {
            SocketAddress clientAddress = socket.getRemoteSocketAddress();
            System.out.println("Handling clieng at "+ clientAddress);
            
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            
            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
